package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.remote.ProductApiClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class ClearCartItemHandler extends AbstractTransHandler {

    @Autowired
    ProductApiClient productApiClient;

    //是否采用异步方式执行
    @Override
    public boolean isAsync() {
        return true;
    }

    @Override
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        Long userId = createOrderContext.getUserId();
        List<Long> buyProductIds = new ArrayList<>();
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        if (cartProductDtoList != null) {
            for (CartProductDto cartProductDto : cartProductDtoList) {
                buyProductIds.add(cartProductDto.getProductId());
            }
        }
        ClearCartItemRequest clearCartItemRequest = new ClearCartItemRequest();
        clearCartItemRequest.setUserId(userId);
        clearCartItemRequest.setProductIds(buyProductIds);

        productApiClient.clearCartItemByUserID(clearCartItemRequest);
        return true;
    }
}
